﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace WinToastr
{
    public class ToastrControl: Control
    {
        private Boolean isTransparent = false;

        /// <summary>
        /// Gets or sets a value indicating whether control is transparent.
        /// </summary>
        public Boolean IsTransparent
        {
            get
            {
                return isTransparent;
            }
            set
            {
                isTransparent = value;
                if (value)
                    this.BackColor = Color.Transparent;
                Invalidate();
            }
        }

        /// <summary>
        /// Notification control.
        /// </summary>
        public ToastrControl()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }

        /// <summary>
        /// Paints the background of the control.
        /// </summary>
        /// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);

            if (!isTransparent || Parent == null)
                return;

            Int32 index = Parent.Controls.GetChildIndex(this);

            for (Int32 i = Parent.Controls.Count - 1; i >= index + 1; i--)
            {
                Control ctrl = Parent.Controls[i];
                if (ctrl.Bounds.IntersectsWith(Bounds) && ctrl.Visible)
                {
                    Bitmap bmp = new Bitmap(ctrl.Width, ctrl.Height);
                    ctrl.DrawToBitmap(bmp, ctrl.ClientRectangle);
                    e.Graphics.TranslateTransform(ctrl.Left - Left, ctrl.Top - Top);
                    e.Graphics.DrawImage(bmp, Point.Empty);
                    e.Graphics.TranslateTransform(Left - ctrl.Left, Top - ctrl.Top);
                    bmp.Dispose();
                }
            }
        }
    }
}
